package zzps.exeed.kernel;

import org.slf4j.Logger;
import zzps.exeed.kernel.tool.LogTool;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.time.Duration;

public class Exeed {


    private static Logger logger = LogTool.getLogger();
    private static ExeedApp exeedApp;

    public static ExeedApp start(Class<?> source, String[] args) {
        if (source == null){
            throw new ExeedException("启动类不能为空!");
        }
        if (exeedApp != null){
            return exeedApp;
        }
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        String pid = runtimeMXBean.getName().split("@")[0];
        System.setProperty("PID", pid);
        logger.info("Exeed app starting ...");
        long startTime = System.currentTimeMillis();
        try {
            exeedApp = new ExeedApp(source,args);
            exeedApp.start();
        } catch (Exception e) {
            stop();
            throw new RuntimeException(e);
        }
        Duration duration = Duration.ofMillis(System.currentTimeMillis() - startTime);
        logger.info("Started App in {}.{} seconds",duration.toSecondsPart(),duration.toMillisPart());
        Runtime.getRuntime().addShutdownHook(new Thread(() -> stop()));
        return exeedApp;
    }

    public static void stop(){
        if (exeedApp == null){
            return;
        }
        exeedApp.stop();
    }
}
